﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace SemanticEx
{
	public class Validator
	{
		#region Constructors

		public Validator(Regex regex)
		{
			Regex = regex;
			Validations = new Dictionary<string, IList<Func<string, bool>>>();
		}

		public Validator(Validator clone)
			: this(clone.Regex)
		{
			foreach (var pair in clone.Validations)
			{
				foreach (var validation in pair.Value)
				{
					AddValidation(pair.Key, validation);
				}
			}
		}

		#endregion

		#region Properties

		public Regex Regex { get; private set; }

		private IDictionary<string, IList<Func<string, bool>>> Validations { get; set; }

		#endregion

		#region Methods

		public void AddValidation(string groupName, Func<string, bool> validation)
		{
			if (!Validations.ContainsKey(groupName))
			{
				Validations[groupName] = new List<Func<string, bool>>();
			}
			Validations[groupName].Add(validation);
		}

		public Validation Match(string input)
		{
			var match = Regex.Match(input);
			Validation validation = null;
			foreach (var pair in Validations)
			{
				foreach (var predicate in pair.Value)
				{
					validation = (validation == null)
						? match.Validate(pair.Key, predicate)
						: validation.Validate(pair.Key, predicate);
				}
			}
			return validation;
		}

		#endregion
	}
}